package com.farm.kaiping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.farm.common.security.SecurityUtils;
import com.farm.kaiping.entity.SysDept;
import com.farm.kaiping.po.SysDeptPO;
import com.farm.kaiping.mapper.SysDeptMapper;
import com.farm.kaiping.service.SysDeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.farm.common.util.StringRange;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理(SysDept)表服务实现类
 *
 * @author zhuhui
 * @since 2024-11-26 22:58:53
 */
@Service
@Slf4j
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {
    
	private LambdaQueryWrapper<SysDept> generateQueryWrapper(SysDeptPO sysDeptPO){
		LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
		// 部门ID
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getDeptId()), SysDept::getDeptId, sysDeptPO.getDeptId());
		queryWrapper.in(ObjectUtil.isNotEmpty(sysDeptPO.getDeptIdList()), SysDept::getDeptId, sysDeptPO.getDeptIdList());
		// 部门名称
		queryWrapper.like(ObjectUtil.isNotEmpty(sysDeptPO.getName()), SysDept::getName, sysDeptPO.getName());
		// 排序
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getSort()), SysDept::getSort, sysDeptPO.getSort());
		// 父级ID
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getParentId()), SysDept::getParentId, sysDeptPO.getParentId());
		queryWrapper.in(ObjectUtil.isNotEmpty(sysDeptPO.getParentIdList()), SysDept::getParentId, sysDeptPO.getParentIdList());
		// 是否删除(0否1是)
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getDelFlag()), SysDept::getDelFlag, sysDeptPO.getDelFlag());
        queryWrapper.eq(ObjectUtil.isEmpty(sysDeptPO.getDelFlag()), SysDept::getDelFlag, 0);
		// 新增时间
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getCreateTime()), SysDept::getCreateTime, sysDeptPO.getCreateTime());
		// 创建人ID
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getCreateUserId()), SysDept::getCreateUserId, sysDeptPO.getCreateUserId());
		// 创建人姓名
		queryWrapper.like(ObjectUtil.isNotEmpty(sysDeptPO.getCreateUserName()), SysDept::getCreateUserName, sysDeptPO.getCreateUserName());
		// 更新时间
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getUpdateTime()), SysDept::getUpdateTime, sysDeptPO.getUpdateTime());
		// 更新人ID
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getUpdateUserId()), SysDept::getUpdateUserId, sysDeptPO.getUpdateUserId());
		// 更新人姓名
		queryWrapper.like(ObjectUtil.isNotEmpty(sysDeptPO.getUpdateUserName()), SysDept::getUpdateUserName, sysDeptPO.getUpdateUserName());
		// 租户ID
		queryWrapper.eq(ObjectUtil.isNotEmpty(sysDeptPO.getTenantId()), SysDept::getTenantId, sysDeptPO.getTenantId());
		// 创建时间时间区间查询
		queryWrapper.ge(ObjectUtil.isNotEmpty(StringRange.getOne(sysDeptPO.getCreateTimeBetween(),0)), SysDept::getCreateTime,StringRange.getOne(sysDeptPO.getCreateTimeBetween(),0));
		queryWrapper.le(ObjectUtil.isNotEmpty(StringRange.getOne(sysDeptPO.getCreateTimeBetween(),1)), SysDept::getCreateTime,StringRange.getOne(sysDeptPO.getCreateTimeBetween(),1));
		// 更新时间时间区间查询
		queryWrapper.ge(ObjectUtil.isNotEmpty(StringRange.getOne(sysDeptPO.getUpdateTimeBetween(),0)), SysDept::getUpdateTime,StringRange.getOne(sysDeptPO.getUpdateTimeBetween(),0));
		queryWrapper.le(ObjectUtil.isNotEmpty(StringRange.getOne(sysDeptPO.getUpdateTimeBetween(),1)), SysDept::getUpdateTime,StringRange.getOne(sysDeptPO.getUpdateTimeBetween(),1));

		queryWrapper.orderByDesc(SysDept::getCreateTime,SysDept::getDeptId);
		return queryWrapper;
	}

	 /**
	  * @describe 分页查询部门管理
	  * @author zhuhui
	  * @date 2024-11-26 22:58:53
	  */
	@Override
	public Page<SysDept> getSysDeptPage(Page page, SysDeptPO sysDeptPO){
		LambdaQueryWrapper<SysDept> queryWrapper = this.generateQueryWrapper(sysDeptPO);
        return this.baseMapper.selectPage(page, queryWrapper);
	}
	
	/**
     * @describe 查询部门管理list
     * @author  zhuhui
     * @date  2024-11-26 22:58:53
     */
	@Override
	public List<SysDept> getSysDeptList(SysDeptPO sysDeptPO){
		LambdaQueryWrapper<SysDept> queryWrapper = this.generateQueryWrapper(sysDeptPO);
        return this.baseMapper.selectList(queryWrapper);
	}
	
	/**
     * @describe 获取一条数据 部门管理
     * @author  zhuhui
     * @date  2024-11-26 22:58:53
     */
	@Override
	public SysDept getSysDept(SysDeptPO sysDeptPO){
		LambdaQueryWrapper<SysDept> queryWrapper = this.generateQueryWrapper(sysDeptPO);
        queryWrapper.last("LIMIT 1");
        return this.baseMapper.selectOne(queryWrapper);
	}

    /**
     * @describe 新增部门管理
     * @author  zhuhui
     * @date  2024-11-26 22:58:53
     */
	@Override
	public Integer saveSysDept(SysDeptPO sysDeptPO) {
		if(ObjectUtil.isEmpty(sysDeptPO.getParentId())){
			throw new RuntimeException("父级ID为空");
		}
		if (ObjectUtil.isEmpty(sysDeptPO.getName())){
			throw new RuntimeException("部门名称为空");
		}
		if(ObjectUtil.isEmpty(sysDeptPO.getSort())){
			sysDeptPO.setSort(0);
		}
        sysDeptPO.setDelFlag(0);
		sysDeptPO.setTenantId(SecurityUtils.getUser().getTenantId());// 租户ID
		sysDeptPO.setCreateTime(LocalDateTime.now());
		sysDeptPO.setCreateUserId(SecurityUtils.getUser().getUserId());// 创建人
		sysDeptPO.setCreateUserName(SecurityUtils.getUser().getRealName());// 创建人
		sysDeptPO.setUpdateTime(LocalDateTime.now());
		SysDept sysDept = BeanUtil.copyProperties(sysDeptPO, SysDept.class);
		this.save(sysDept);
		return sysDept.getDeptId();
	}

	/**
     * @describe 修改部门管理
     * @author  zhuhui
     * @date  2024-11-26 22:58:53
     */
	@Override
	public String updateSysDept(SysDeptPO sysDeptPO) {
		if (ObjectUtil.isEmpty(sysDeptPO.getDeptId())) {
			throw new RuntimeException("id为空");
		}

		sysDeptPO.setUpdateUserId(SecurityUtils.getUser().getUserId());// 更新人
		sysDeptPO.setUpdateUserName(SecurityUtils.getUser().getRealName());// 更新人
		sysDeptPO.setUpdateTime(LocalDateTime.now());
		SysDept sysDept = BeanUtil.copyProperties(sysDeptPO, SysDept.class);
		this.updateById(sysDept);
		return "修改成功";
	}

	/**
     * @describe 通过id删除部门管理
     * @author  zhuhui
     * @date  2024-11-26 22:58:53
     */
	@Override
	public String removeSysDept(SysDeptPO sysDeptPO) {
		if (ObjectUtil.isEmpty(sysDeptPO.getBatchDel())) {
			throw new RuntimeException("删除数据未选择");
		}
		LambdaUpdateWrapper<SysDept> removeWrapper = new LambdaUpdateWrapper<>();
		removeWrapper.in(SysDept::getDeptId, sysDeptPO.getBatchDel());
		removeWrapper.set(SysDept::getDelFlag,1);
		removeWrapper.set(SysDept::getUpdateUserId,SecurityUtils.getUser().getUserId());// 更新人
		removeWrapper.set(SysDept::getUpdateUserName,SecurityUtils.getUser().getRealName());// 更新人
		removeWrapper.set(SysDept::getUpdateTime,LocalDateTime.now());

		this.update(removeWrapper);
		return "删除成功";
	}

	@Override
	public List<SysDept> treeSysDept(SysDeptPO sysDeptPO) {
		sysDeptPO.setRootId(ObjectUtil.isEmpty(sysDeptPO.getRootId())?0:sysDeptPO.getRootId());
		List<SysDept> sysDeptList = this.getSysDeptList(sysDeptPO);
		sysDeptList = sysDeptList.stream().sorted(Comparator.comparing(SysDept::getSort).reversed()).collect(Collectors.toList());
		List<SysDept> collect = sysDeptList.stream()
				.filter(sysDept -> ObjectUtil.equal(sysDept.getParentId(),sysDeptPO.getRootId()))
				.collect(Collectors.toList());
		for (SysDept sysDept : collect) {
			sysDept.setChildren(buildChildren(sysDept.getDeptId(),sysDeptList));
		}
		return collect;
	}

	private static List<SysDept> buildChildren(Integer id, List<SysDept> sysDeptList) {
		List<SysDept> children = new ArrayList<>();
		for (SysDept sysDept : sysDeptList) {
			if (ObjectUtil.isEmpty(sysDept.getParentId()) || ObjectUtil.equal(sysDept.getParentId(),0)){
				continue;
			}
			if (sysDept.getParentId().equals(id)){
				children.add(sysDept);
			}
		}
		for (SysDept child : children) {
			child.setChildren(buildChildren(child.getDeptId(),sysDeptList));
		}
		return children;
	}

	
}

